import { MVC } from "../../framework/MVC";
import { AlertManager, AlertType } from "../../alert/AlertManager";
import { Util } from "../../utils/Util";
import { GameVoManager } from "../../manager/GameVoManager";
import { Manager } from "../../manager/Manager";
import NetAdapter from "../../adpapter/NetAdapter";
import { Cfg } from "../../config/Cfg";
import GlobalData from "../../GlobalData";
import { Notifier } from "../../framework/Notifier";
import { ListenID } from "../../ListenID";
import { AudioType } from "../../manager/AudioManager";
import { UIManager } from "../../framework/UIManager";
import { Common_UIPath } from "../../common/Common_Define";
import { UserVo } from "../../shareData/UserVo";
import RewardTaskModel from "../rewardtask/RewardTaskModel";
import DeviceManager from "../../manager/DeviceManager";
import { Const } from "../../config/Const";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PersonView extends MVC.BaseView {
  @property(cc.Label)
  nick_name: cc.Label = null;

  @property(cc.Label)
  uidNum: cc.Label = null;

  @property(cc.Label)
  battleNum: cc.Label = null;

  @property(cc.Label)
  stageText: cc.Label = null;

  @property(cc.Label)
  battleRankNum: cc.Label = null;

  @property(cc.Label)
  stageRankNum: cc.Label = null;

  @property(cc.Label)
  bossRankNum: cc.Label = null;

  @property(cc.Sprite)
  spExpBar: cc.Sprite = null;

  @property(cc.EditBox)
  dailiInput: cc.EditBox = null;

  @property(cc.Button)
  dailiConfirm: cc.Button = null;

  @property(cc.Label)
  shareNum: cc.Label = null;

  @property(cc.Sprite)
  avatar: cc.Sprite;

  @property(cc.Sprite)
  avatarApp: cc.Sprite;

  @property(cc.Label)
  uidNumApp: cc.Label;

  @property(cc.Label)
  nick_nameApp: cc.Label;

  @property(cc.Label)
  battleNumApp: cc.Label;

  @property(cc.Label)
  shareNumApp: cc.Label;

  @property(cc.Node)
  app: cc.Node;

  @property(cc.Node)
  box_btn_zhuxiao: cc.Node;

  @property(cc.Label)
  label_today: cc.Label;

  @property(cc.Label)
  label_yesterday: cc.Label;

  protected changeListener(enable: boolean): void {
    //Notifier.changeListener(enable, NotifyID.Game_Update, this.onUpdate, this);
  }

  /*
   * 打开界面回调，每次打开只调用一次
   */
  public onOpen(args: any): void {
    if(Util.isDouyinGame() || Util.isKuaishouGame())
    {
      this.app.active = false
    }else
    {
      this.app.active = true
    }
    Util.isAndroid()?(this.box_btn_zhuxiao.active = true) : (this.box_btn_zhuxiao.active = true);
    super.onOpen(args);
    this.setInfo(args);

    let url = GameVoManager.getInstance.myUserVo.avatar_url;
    Util.loadRemoteSf(url, this.avatar);
    Util.loadRemoteSf(url, this.avatarApp);
    NetAdapter.getFriendUser({}).then((res) => {
      console.log("获取好友列表", res);
      if (res) {
        let myfriendcount =  Object.keys(res).length;//info[0].myfriendcount;
        // this.shareNum.string = Object.keys(myfriendlist).length + "";
        this.shareNum.string = myfriendcount + "";
        this.shareNumApp.string = myfriendcount + "";
      }
    });
    if(Util.isIOS()&&GlobalData.inst.tempHide){
      this.label_today.node.active = false;
      this.label_yesterday.node.active = false;
    }else{
      this.label_today.node.active = true;
      this.label_yesterday.node.active = true;
      NetAdapter.getUserInfo({uid:GlobalData.inst.uid}).then((res) => {
        Util.logExt(res, "获取邀请好友信息");
        if (res) {
          this.label_today.string ="今日邀请人数："+ res.today_con;
          this.label_yesterday.string = "昨日邀请人数："+res.yesterday_con;
        }
      });
    }
  }

  public setInfo(args) {
    if (
      GlobalData.inst.agent_uid &&
      GlobalData.inst.agent_uid != "" &&
      GlobalData.inst.agent_uid != "0"
    ) {
      this.dailiInput.string = GlobalData.inst.agent_uid;
      this.dailiInput.enabled = false;
      this.dailiConfirm.node.active = false;
    }
    // this.uidNum.string = Util.normalName(GlobalData.inst.uid, 2);
    this.uidNum.string = GlobalData.inst.uid;
    this.uidNumApp.string = GlobalData.inst.uid;
    this.battleNum.string = GameVoManager.getInstance.getBattle() + "";
    this.battleNumApp.string = GameVoManager.getInstance.getBattle() + "";
    this.nick_name.string = GameVoManager.getInstance.myUserVo.nick_name;
    this.nick_nameApp.string = GameVoManager.getInstance.myUserVo.nick_name;
    let chapterids = Util.levelToChapterId(
      GameVoManager.getInstance.myUserVo.top_level
    );
    this.stageText.string = `第${chapterids[0]}章${chapterids[1]}波`;
    let param: string[] = [
      "newbattle.forever",
      "newlevel.forever",
      "bosslevel.forever",
    ];
    let rankinfo: string[] = ["battleRankNum", "stageRankNum", "bossRankNum"];
    NetAdapter.getRankInfoByKey(param).then((res) => {
      if (res.data) {
        for (let i = 0; i < param.length; i++) {
          let battledata = res.data[param[i]];
          if (battledata) {
            if (battledata.self_rank) {
              this[rankinfo[i]].string = `No.${battledata.self_rank}`;
              this[rankinfo[i]].node.color = cc.Color.WHITE;
            } else {
              this[rankinfo[i]].string = "暂无排名";
              this[rankinfo[i]].node.color = cc.Color.WHITE.fromHEX("#E25744");
            }
          } else {
            this[rankinfo[i]].string = "暂无排名";
            this[rankinfo[i]].node.color = cc.Color.WHITE.fromHEX("#E25744");
          }
        }
      }
    });
    //test

    let roleVO = GameVoManager.getInstance.myUserVo;
    let curLv = roleVO.roleLv;
    let curExp = roleVO.curExp;
    let nextLvCfg = Cfg.RoleLevel.get(curLv + 1);
    let max = nextLvCfg ? nextLvCfg.exp : 1;
    max = max == 0 ? 1 : max;
    let prog = cc.find(`douyingUI/expProgressBar`, this.node);
    let lblLevel = cc.find(`imgPro6/lblLevel`, prog);
    max = max == 0 ? 1 : max;
    lblLevel.getComponent(cc.Label).string = curLv + ``;
    this.setExpBarPercent(curExp / max);
  }
  /*
   * 关闭界面回调，每次打开只调用一次
   */
  public onClose(): void {
    super.onClose();
    Manager.audio.playAudio(501);
  }

  private _pasteBtnId: string = "";
  /** 复制到剪贴板(原生平台可用) */
  uiPasteBoard(e, d) {
    let str = "";
    Manager.audio.playAudio(501);
    if (this._pasteBtnId == d) return;
    str = "";
    this._pasteBtnId == d; //不能一重复点复制，会卡死
    DeviceManager.inst.copyText(GlobalData.inst.uid + "", () => {
      AlertManager.showNormalTips("复制到剪贴板成功");
    }, () => {
      AlertManager.showNormalTips("复制到剪贴板失败");
    });
  }

  setExpBarPercent(value: number) {
    this.spExpBar.fillRange = value;
  }

  onDaliConfirm() {
    if (GlobalData.inst.agent_uid != "" && GlobalData.inst.agent_uid != "0") {
      AlertManager.showNormalTips("你已经绑定过了！");
    } else {
      let agent_uid = this.dailiInput.string;
      NetAdapter.userUpdateDaili({ agent_uid: agent_uid })
        .then((res) => {
          Util.logExt(res, "绑定成功");
          GlobalData.inst.agent_uid = agent_uid;
          AlertManager.showNormalTips("绑定成功！");
        })
        .catch((err) => {
          Util.logExt(err, "绑定失败");
          AlertManager.showNormalTips("绑定失败");
        });
    }
  }
  // 用户协议
  onUserProtocol(event, custom_data) {
    UIManager.Open(
      Common_UIPath.UserProtocolView,
      MVC.eTransition.Default,
      MVC.eUILayer.Tips
    );
    Manager.audio.playAudio(501, AudioType.UI);
  }

  // 隐私协议
  onPrivacyProtocol() {
    UIManager.Open(
      Common_UIPath.PrivacyView,
      MVC.eTransition.Default,
      MVC.eUILayer.Tips
    );
    Manager.audio.playAudio(501, AudioType.UI);
  }
  // 清除token，强制退出,关闭所有预制体
  public clearToken() {
    GlobalData.inst.uid = null;
    GameVoManager.getInstance.stateVo.isGetData = false;
    GameVoManager.getInstance.myUserVo = new UserVo();
    // 清除token
    UIManager.closeAllUI();
    GlobalData.inst.init();
    UIManager.Open(
      Common_UIPath.LoginView,
      MVC.eTransition.Default,
      MVC.eUILayer.Tips
    );

    cc.sys.localStorage.setItem(Const.LOGIN_UID, "");
    cc.sys.localStorage.setItem(Const.LOGIN_TOKEN, "");
    
    Manager.audio.playAudio(501, AudioType.UI);
    this.onClose();
    return
  }


  // 退出登录
  onLogout() {
    this.clearToken()
  }
  //   注销
  onWriteOff() {
    console.log("banDevice  device_id =",GlobalData.inst.device_id)
    AlertManager.showAlert(AlertType.SELECT, {
      reasonDesc: "注销账户",
      wayDesc: "确定注销账户吗？此功能无法撤销",
      confirmText: "确定",
      cancelText: "否",
      confirm: () => {
        // console.log("注销")
        // NetAdapter.writeOff({
        console.log("封禁设备")
        NetAdapter.banDevice({
          device_id: GlobalData.inst.device_id
        }).then((res) => {
            console.log(res);
            Manager.audio.playAudio(501, AudioType.UI);
            console.log("封禁设备成功");
            this.onLogout()
         });
    
         return;
      },
  })
  // return
    
  }
}
